# -*- coding: utf-8 -*-
import datetime
import logging
import os
import subprocess
import time
from flask import request

from service.FileUtils import run_shell
from service.MetastoreService import insert_column_record,get_column_list
from flask import Blueprint

metastore_api = Blueprint('metastore_api', __name__)



# 将文件转换为hive表
def add_new_column_hive(column_name, column_type):
    cur_dir = os.getcwd()
    # cmd = f'nohup  hdfs dfs -put {cur_dir}/upload/{file_name}  oss://emr-datalake.cn-beijing.oss-dls.aliyuncs.com/test/   ;  ' \
    #       f' sh 2>&1 & '

    table_type = ""
    if str.lower(column_type) == "string":
        table_type  = "string"
    elif str.lower(column_type) == "integer":
        table_type = "int"
    elif str.lower(column_type) == "long":
        table_type = "bigint"
    elif str.lower(column_type) == "double":
        table_type = "decimal(10,2)"
    cmd = f'source /opt/Bigdata/bigdata_env ; beeline -e "show create table ods.ods_cc_ad_log_inc_d  ;"'
    result = run_shell(cmd)
    logging.info(f'cmd: {result}')

    cmd = f'source /opt/Bigdata/bigdata_env ; beeline -e "alter table ods.ods_cc_ad_log_inc_d add columns({column_name} {table_type}) ;"'
    logging.info(f'cmd： {cmd}')
    result = run_shell(cmd)
    logging.info(f'cmd: {result}')


@metastore_api.route('/api/private/v1/metastore/column', methods=['POST'])
def add_recommend():
    req_body = request.json
    log_column =   req_body['logcolumn']
    table_column = req_body['tablecolumn']
    log_type =     req_body['logtype']
    table_type =   req_body['tabletype']
    comment =     req_body['comment']

    created_time = time.strftime("%Y-%m-%d %H:%M:%S")

    column_list = [(log_column, table_column, log_type,table_type,comment, created_time)]

    insert_column_record(column_list)

    add_new_column_hive(table_column, table_type)

    logging.info("POST /metastore/column接口调用成功")
    return {
        "meta": {"msg": "成功", "status": 200}
    }

@metastore_api.route('/api/private/v1/metastore/column', methods=['GET'])
def get_metastore_column():
    cur_page_num = request.args.get("pagenum")
    logging.info(f"page_num : {cur_page_num}")

    column_list = get_column_list(cur_page_num)
    result = []
    for item in column_list:
        result.append({
            "id" : item[0],
            "log_column": item[1],
            "table_column": item[2],
            "log_type": item[3],
            "table_type": item[4],
            "comment": item[5],
            "created_time": item[6]
        })

    logging.info("GET /column接口调用成功")
    return {
        "data" : {
            "columns": result ,
            "total" : 100,
            "pagenum": 1
        },
        "meta": {"msg": "成功", "status": 200}
    }

